package ma.xin.shi;

import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.custom.ScrolledComposite;

import ma.xin.shi.configurations.SomeipAction.SomeipActionEntry;
import ma.xin.shi.configurations.SomeipAction.MulticastEntry;
import ma.xin.shi.table.TableManager;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.dialogs.MessageDialog;
//import ma.xin.shi.ConfigurationManager;
import ma.xin.shi.configurations.SomeipAction.SomeipActionConfig;


public class SomeipActionDisplay {
	
	private static Text UnicastPort;
	private static Text UnicastProtocol;
	private static Table MulcastTable;
	private static Table ActiveTable;

    public static void display(Composite workArea) {
        for (Control control : workArea.getChildren()) {
            control.dispose();
        }

        ScrolledComposite[] composites = addSomeipComposite(workArea);

        SomeipGlobalAreaCtrl(composites[0]);
        SomeipActionAreaCtrl(composites[1]);
        
        initializeUIWithConfig();

        workArea.layout(true, true);
    }

    private static ScrolledComposite[] addSomeipComposite(Composite parent) {
        parent.setLayout(new GridLayout(1, false));

        // 第一个ScrolledComposite
        ScrolledComposite someipGlobalComposite = new ScrolledComposite(parent, 
                SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
        GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
        gridData.heightHint = 150;
        someipGlobalComposite.setLayoutData(gridData);
        
        // 第二个ScrolledComposite
        ScrolledComposite someipActiveComposite = new ScrolledComposite(parent, 
                SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
        someipActiveComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        return new ScrolledComposite[] {someipGlobalComposite, someipActiveComposite};
    }

    private static void SomeipGlobalAreaCtrl(ScrolledComposite parent) {
        // 创建内容Composite
        Composite content = new Composite(parent, SWT.NONE);
        content.setLayout(new GridLayout(1, false));
        GridData contentData = new GridData(SWT.FILL, SWT.FILL, true, true);
        content.setLayoutData(contentData);

        Label contentLabel = new Label(content, SWT.NONE);
        contentLabel.setText("Someip Global Config");
        contentLabel.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
        AutorsarCommonUtils.setLabelFontStyle(contentLabel, SWT.BOLD | SWT.ITALIC);

        Composite UnicastComposite = new Composite(content, SWT.NULL);
        UnicastComposite.setLayout(new GridLayout(2, false));
        UnicastPort = AutorsarCommonUtils.createLabeledText(UnicastComposite, "UnicastPort Number");
        UnicastProtocol = AutorsarCommonUtils.createLabeledText(UnicastComposite, "UnicastProtocol type");

        Composite UnicastTableComposite = new Composite(content, SWT.NULL);
        SomeipMulcastTableAdd(UnicastTableComposite);

        someipMulticastButtonAdd(UnicastTableComposite);

        Composite GlobalButtonArea = new Composite(content, SWT.NULL);
        someipGlobalButtonAdd(GlobalButtonArea);

        // 强制布局更新
        content.layout(true, true);

        // 设置ScrolledComposite的内容和最小尺寸
        parent.setContent(content);
        parent.setExpandHorizontal(true);
        parent.setExpandVertical(true);
        Point minSize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);
        parent.setMinSize(minSize);
    }

    private static void SomeipMulcastTableAdd(Composite parent) {
        parent.setLayout(new GridLayout(1, false));

        Label SomeipMulcastLabel = new Label(parent, SWT.NONE);
        SomeipMulcastLabel.setText("Someip Multicast config");
        SomeipMulcastLabel.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
        
        AutorsarCommonUtils.setLabelFontStyle(SomeipMulcastLabel, SWT.BOLD | SWT.ITALIC);

        MulcastTable = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION);
        MulcastTable.setHeaderVisible(true);
        MulcastTable.setLinesVisible(true);

        // 设置列头
        String[] columnNames = {"index", "VLAN ID", "SD Multicast Address", "SD Port Number", "Protocol"};
        for (String name : columnNames) {
            TableColumn column = new TableColumn(MulcastTable, SWT.NONE);
            column.setText(name);
            column.setWidth(150);
        }

        // 设置布局数据：占满剩余空间
        GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
        gridData.heightHint = 100;  // 固定高度，让表格显示约6行空白区域
        MulcastTable.setLayoutData(gridData);

        // 设置为可编辑
        TableManager.setupEditableTable(MulcastTable, new TableManager.EditableTableConfig() {
            @Override
            public boolean isComboColumn(int columnIndex) {
                return columnIndex == 4; // 第4列用下拉框
            }

            @Override
            public String[] getComboItems(int columnIndex) {
                if (columnIndex == 4) {
                    return new String[]{"TCP", "UDP", "TCP&UDP"};
                }
                return null;
            }
        });
    }

    
    private static void someipMulticastButtonAdd(Composite parent) {
    	
    	Button MulButton[] = AutorsarCommonUtils.createButtonsAtBottomRight(parent, "Add", "Del");
    	Button btnAdd = MulButton[0];
    	Button btnRemove = MulButton[1];
    	
    	 // 新增按钮逻辑
        btnAdd.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                int index = MulcastTable.getItemCount();
                TableItem item = new TableItem(MulcastTable, SWT.NONE);
                item.setText(0, String.valueOf(index));
                item.setText(1, "name" + index);
                item.setText(2, "0");
                //item.setText(2, String.valueOf(index));
            }
        });

        // 删除按钮逻辑
        btnRemove.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                TableItem[] selectedItems = MulcastTable.getSelection();
                for (TableItem item : selectedItems) {
                    item.dispose();
                }
                TableManager.renumberTableItems(MulcastTable);
            }
        });
    }

    private static void someipGlobalButtonAdd(Composite parent) {
        parent.setLayout(new GridLayout(1, false));
        GridData parentData = new GridData(SWT.FILL, SWT.FILL, true, true);
        parent.setLayoutData(parentData);

        Button[] buttons = AutorsarCommonUtils.createButtonsAtBottomRight(parent, "Save", "Cancel");
        Button btnSave = buttons[0];
        Button btnCancel = buttons[1];

        btnSave.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                saveCurrentGlobalConfig();
                MessageDialog.openInformation(parent.getShell(), "提示", "数据已保存！");
            }
        });

        btnCancel.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                // 取消编辑，恢复原始配置
                restoreGlobalDataFromConfig();
                //MessageDialog.openInformation(parent.getShell(), "提示", "已撤销修改，恢复原始配置！");
            }
        });
    }

    private static void someipActivelButtonAdd(Composite parent) {
        parent.setLayout(new GridLayout(1, false));
        GridData parentData = new GridData(SWT.FILL, SWT.FILL, true, true);
        parent.setLayoutData(parentData);

        Button[] buttons = AutorsarCommonUtils.createButtonsAtBottomRight(parent, "Save", "Cancel");
        Button btnSave = buttons[0];
        Button btnCancel = buttons[1];

        btnSave.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
            	saveCurrentSomeipActiveConfig();
                MessageDialog.openInformation(parent.getShell(), "提示", "数据已保存！");
            }
        });

        btnCancel.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                // 取消操作：恢复原始配置
                restoreActiveTableFromConfig();
                //MessageDialog.openInformation(parent.getShell(), "提示", "已撤销修改，恢复原始 someip active 配置！");
            }
        });
    }

    private static void SomeipActionAreaCtrl(ScrolledComposite parent) {
        // 创建内容Composite
        Composite content = new Composite(parent, SWT.NONE);
        content.setLayout(new GridLayout(1, false));

        Label contentLabel = new Label(content, SWT.NONE);
        contentLabel.setText("Someip Active Config");
        contentLabel.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
        AutorsarCommonUtils.setLabelFontStyle(contentLabel, SWT.BOLD | SWT.ITALIC);

        
        
        Composite actTableComposite = new Composite(content, SWT.NULL);
        SomeipActiveTableAdd(actTableComposite);

        SomeipActiveButtonAdd(actTableComposite);
        
        Composite ActivelButtonArea = new Composite(content, SWT.NULL);
        someipActivelButtonAdd(ActivelButtonArea);
        
        // 设置ScrolledComposite的内容和最小尺寸
        parent.setContent(content);
        parent.setExpandHorizontal(true);
        parent.setExpandVertical(true);
        parent.setMinSize(content.computeSize(SWT.DEFAULT, SWT.DEFAULT));
    }

    private static void SomeipActiveTableAdd(Composite parent) {
        // 父容器横向撑满，允许子组件填充
        GridData parentData = new GridData(SWT.FILL, SWT.FILL, true, true);
        parent.setLayoutData(parentData);

        // 设置 parent 的 layout，允许内部组件横向撑满
        parent.setLayout(new GridLayout(1, false));

        // 创建表格
        ActiveTable = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION);
        ActiveTable.setHeaderVisible(true);
        ActiveTable.setLinesVisible(true);

        // 使用 TableLayout 来自动分配列宽
        TableLayout tableLayout = new TableLayout();
        ActiveTable.setLayout(tableLayout);

        String[] columnNames = {"index",
            "Service Name", "Service ID", "Instance ID", "Major Version", "Minor Version",
            "TTL", "VID", "VName", "VPriority", "TransportProtocol", "Server", "ServerIP",
            "ServerIPSubMask", "ServerPort", "Client", "ClientID", "ClientIPUni",
            "ClientIPSubMask", "ClientPort", "SList", "CList"
        };

        for (int i = 0; i < columnNames.length; i++) {
            TableColumn column = new TableColumn(ActiveTable, SWT.NONE);
            column.setText(columnNames[i]);

            // 关键列设置较宽
            if (i == 1 || i == 4 || i ==5) {
                column.setWidth(100); // 服务名、服务器、客户端等列宽一些
            } else if (i == 2 || i == 8) {
                column.setWidth(80);  // TTL、VID、优先级等数值列可以窄些
            } else if (i == 0 || i ==6 || i == 7) {
            	column.setWidth(50);
            } else if (i ==10 || i == 13 || i == 18) {
            	column.setWidth(120);
            } else {
                column.setWidth(90); // 默认宽度
            }
        }

        /* do not need set avarage width
        for (String name : columnNames) {
            TableColumn column = new TableColumn(ActiveTable, SWT.NONE);
            column.setText(name);
            tableLayout.addColumnData(new ColumnWeightData(1));  // 均匀分布宽度
        }*/

        // 表格横向撑满 parent，并设定高度提示
        GridData tableData = new GridData(SWT.FILL, SWT.FILL, true, true);
        tableData.heightHint = 100;  // 可选：控制表格显示约3~4行的高度
        ActiveTable.setLayoutData(tableData);

        // 设置为可编辑（根据你的需求保留）
        String[] multiSelectOptions = {
                "VechileBody", "VCC_MCU", "VCC_MPU", "TMS", "VCU", "FLZCU", "FRZCU", "RZCU", "ICC",
                "ICC_8155_Android", "ICC_8155_QNX", "TBOX", "TBOX_ex", "ADCC", "LCM", "FCM", "FLM",
                "OTA", "AdvanceService", "VDS", "TBOXPackage"
            };

            TableManager.setupEditableTable(ActiveTable, new TableManager.EditableTableConfig() {
                @Override
                public boolean isComboColumn(int columnIndex) {
                    return columnIndex == 10; // TransportProtocol 是 Combo
                }

                @Override
                public String[] getComboItems(int columnIndex) {
                    if (columnIndex == 10) {
                        return new String[]{"TCP", "UDP", "TCP&UDP"};
                    }
                return null;
                }

                @Override
                public boolean isMultiSelectColumn(int columnIndex) {
                    return columnIndex == 20 || columnIndex == 21; // SList & CList 是多选列
                }

                @Override
                public String[] getMultiSelectItems(int columnIndex) {
                    return multiSelectOptions; // 所有多选列共用同一个选项列表
                }
            });
    }

    private static void SomeipActiveButtonAdd(Composite parent) {
    	Button MulButton[] = AutorsarCommonUtils.createButtonsAtBottomRight(parent, "Add", "Del");
    	Button btnAdd = MulButton[0];
    	Button btnRemove = MulButton[1];

    	 // 新增按钮逻辑
        btnAdd.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                int index = ActiveTable.getItemCount();
                TableItem item = new TableItem(ActiveTable, SWT.NONE);
                item.setText(0, String.valueOf(index));
            }
        });

        // 删除按钮逻辑
        btnRemove.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                TableItem[] selectedItems = ActiveTable.getSelection();
                for (TableItem item : selectedItems) {
                    item.dispose();
                }
                TableManager.renumberTableItems(ActiveTable);
            }
        });
    }

    private static void saveCurrentGlobalConfig() {
        // 获取配置单例
        SomeipActionConfig config = ConfigurationManager.getInstance().getSomeipActionConfig();

        // 1. 获取UnicastPort
        String unicastPortValue = UnicastPort.getText().trim();
        if (unicastPortValue.isEmpty()) {
            System.out.println("Unicast Port 不能为空");
            return;
        }
        config.setUnicastPort(unicastPortValue);

        // 2. 获取UnicastProtocol
        String unicastProtocolValue = UnicastProtocol.getText().trim();
        if (unicastProtocolValue.isEmpty()) {
            System.out.println("Unicast Protocol 不能为空");
            return;
        }
        config.setUnicastProtocol(unicastProtocolValue);

        // 3. 清空 multicastEntries 并从表格中加载新数据
        config.getMulticastEntries().clear();

        for (int i = 0; i < MulcastTable.getItemCount(); i++) {
            TableItem item = MulcastTable.getItem(i);

            MulticastEntry entry = new MulticastEntry();
            entry.setVlanId(item.getText(1));             // VLAN ID
            entry.setSdMulticastAddress(item.getText(2)); // SD Multicast Address
            entry.setSdPortNumber(item.getText(3));       // SD Port Number
            entry.setProtocol(item.getText(4));           // Protocol

            config.addMulticastEntry(entry); // 使用已有的 addMulticastEntry 方法
        }

        // 提示用户
        //MessageDialog.openInformation(MulcastTable.getShell(), "提示", "全局配置已保存！");
    }

    /**
     * 从配置中恢复全局部分的数据到 UI 上（用于取消修改）
     */
    public static void restoreGlobalDataFromConfig() {
        SomeipActionConfig config = ConfigurationManager.getInstance().getSomeipActionConfig();

        // 恢复 UnicastPort 和 UnicastProtocol
        if (UnicastPort != null && !UnicastPort.isDisposed()) {
            UnicastPort.setText(config.getUnicastPort());
        }

        if (UnicastProtocol != null && !UnicastProtocol.isDisposed()) {
            UnicastProtocol.setText(config.getUnicastProtocol());
        }

        // 恢复 MulcastTable 表格内容
        if (MulcastTable != null && !MulcastTable.isDisposed()) {
            MulcastTable.removeAll();

            for (MulticastEntry entry : config.getMulticastEntries()) {
                TableItem item = new TableItem(MulcastTable, SWT.NONE);
                item.setText(0, String.valueOf(MulcastTable.getItemCount())); // index 自动递增
                item.setText(1, entry.getVlanId());
                item.setText(2, entry.getSdMulticastAddress());
                item.setText(3, entry.getSdPortNumber());
                item.setText(4, entry.getProtocol());
            }
        }
    }

    /**
     * 将 ActiveTable 表格中的数据保存到 SomeipActionConfig 的 activeEntries 中
     */
    private static void saveCurrentSomeipActiveConfig() {
        SomeipActionConfig config = ConfigurationManager.getInstance().getSomeipActionConfig();

        // 清空旧数据
        config.getActiveEntries().clear();

        // 遍历表格，逐行读取并保存到模型
        for (int i = 0; i < ActiveTable.getItemCount(); i++) {
            TableItem item = ActiveTable.getItem(i);
            SomeipActionEntry entry = new SomeipActionEntry();

            // 设置字段
            entry.setServiceName(item.getText(1));          // Service Name
            entry.setServiceId(item.getText(2));            // Service ID
            entry.setInstanceId(item.getText(3));           // Instance ID
            entry.setMajorVersion(item.getText(4));         // Major Version
            entry.setMinorVersion(item.getText(5));         // Minor Version
            entry.setTtl(item.getText(6));                  // TTL
            entry.setVid(item.getText(7));                  // VID
            entry.setVName(item.getText(8));                // VName
            entry.setVPriority(item.getText(9));            // VPriority
            entry.setTransportProtocol(item.getText(10));   // TransportProtocol
            entry.setServer(item.getText(11));              // Server
            entry.setServerIp(item.getText(12));            // ServerIP
            entry.setServerIpSubMask(item.getText(13));     // ServerIPSubMask
            entry.setServerPort(item.getText(14));          // ServerPort
            entry.setClient(item.getText(15));              // Client
            entry.setClientId(item.getText(16));            // ClientID
            entry.setClientIpUni(item.getText(17));         // ClientIPUni
            entry.setClientIpSubMask(item.getText(18));     // ClientIPSubMask
            entry.setClientPort(item.getText(19));          // ClientPort

            // 处理 sList 和 cList（多选字段）
            String[] sListArray = item.getText(20).split(", ");
            entry.setsList(new ArrayList<>(List.of(sListArray)));

            String[] cListArray = item.getText(21).split(", ");
            entry.setcList(new ArrayList<>(List.of(cListArray)));

            // 添加进配置
            config.addActiveEntry(entry);
        }

        System.out.println("Active Entries 已保存到配置！");
    }

    /**
     * 从配置中恢复 active 表格的数据（用于取消修改）
     */
    public static void restoreActiveTableFromConfig() {
        SomeipActionConfig config = ConfigurationManager.getInstance().getSomeipActionConfig();

        if (ActiveTable != null && !ActiveTable.isDisposed()) {
            ActiveTable.removeAll(); // 清空当前表格

            for (SomeipActionEntry entry : config.getActiveEntries()) {
                TableItem item = new TableItem(ActiveTable, SWT.NONE);

                // 设置各列文本
                item.setText(0, String.valueOf(ActiveTable.getItemCount())); // index 自动递增
                item.setText(1, entry.getServiceName());
                item.setText(2, entry.getServiceId());
                item.setText(3, entry.getInstanceId());
                item.setText(4, entry.getMajorVersion());
                item.setText(5, entry.getMinorVersion());
                item.setText(6, entry.getTtl());
                item.setText(7, entry.getVid());
                item.setText(8, entry.getVName());
                item.setText(9, entry.getVPriority());
                item.setText(10, entry.getTransportProtocol());
                item.setText(11, entry.getServer());
                item.setText(12, entry.getServerIp());
                item.setText(13, entry.getServerIpSubMask());
                item.setText(14, entry.getServerPort());
                item.setText(15, entry.getClient());
                item.setText(16, entry.getClientId());
                item.setText(17, entry.getClientIpUni());
                item.setText(18, entry.getClientIpSubMask());
                item.setText(19, entry.getClientPort());

                // sList 和 cList 转换为字符串显示
                item.setText(20, String.join(", ", entry.getsList()));
                item.setText(21, String.join(", ", entry.getcList()));
            }
        }
    }

    private static void loadGlobalDataToUI() {
        SomeipActionConfig config = ConfigurationManager.getInstance().getSomeipActionConfig();

        // 设置文本框
        if (UnicastPort != null && !UnicastPort.isDisposed()) {
            UnicastPort.setText(config.getUnicastPort() != null ? config.getUnicastPort() : "");
        }

        if (UnicastProtocol != null && !UnicastProtocol.isDisposed()) {
            UnicastProtocol.setText(config.getUnicastProtocol() != null ? config.getUnicastProtocol() : "");
        }

        // 设置表格 MulcastTable
        if (MulcastTable != null && !MulcastTable.isDisposed()) {
            MulcastTable.removeAll();
            int index = 0;
            for (MulticastEntry entry : config.getMulticastEntries()) {
                TableItem item = new TableItem(MulcastTable, SWT.NONE);

                item.setText(0, String.valueOf(index++));

                if (entry.getVlanId() != null && !entry.getVlanId().isEmpty()) {
                    item.setText(1, String.join(", ", entry.getVlanId()));
                } else {
                    item.setText(1, "");
                }
                
                if (entry.getSdMulticastAddress() != null && !entry.getSdMulticastAddress().isEmpty()) {
                    item.setText(2, String.join(", ", entry.getSdMulticastAddress()));
                } else {
                    item.setText(2, "");
                }

                if (entry.getSdPortNumber() != null && !entry.getSdPortNumber().isEmpty()) {
                    item.setText(3, String.join(", ", entry.getSdPortNumber()));
                } else {
                    item.setText(3, "");
                }
                
                if (entry.getProtocol() != null && !entry.getProtocol().isEmpty()) {
                    item.setText(4, String.join(", ", entry.getProtocol()));
                } else {
                    item.setText(4, "");
                }
            }
        }
    }
    
    /**
     * 从配置中加载 active 表格数据到 ActiveTable
     */
    private static void loadActiveTableToUI() {
        SomeipActionConfig config = ConfigurationManager.getInstance().getSomeipActionConfig();
        List<SomeipActionEntry> entries = config.getActiveEntries();

        if (ActiveTable == null || ActiveTable.isDisposed()) {
            return;
        }

        ActiveTable.removeAll();

        int index = 0;
        for (SomeipActionEntry entry : entries) {
            TableItem item = new TableItem(ActiveTable, SWT.NONE);

            // 自动编号（第0列）
            item.setText(0, String.valueOf(index++));

            // 统一使用工具方法处理可能为null的字段
            item.setText(1, getSafeText(entry.getServiceName()));
            item.setText(2, getSafeText(entry.getServiceId()));
            item.setText(3, getSafeText(entry.getInstanceId()));
            item.setText(4, getSafeText(entry.getMajorVersion()));
            item.setText(5, getSafeText(entry.getMinorVersion()));
            item.setText(6, getSafeText(entry.getTtl()));
            item.setText(7, getSafeText(entry.getVid()));
            item.setText(8, getSafeText(entry.getVName()));
            item.setText(9, getSafeText(entry.getVPriority()));
            item.setText(10, getSafeText(entry.getTransportProtocol()));
            item.setText(11, getSafeText(entry.getServer()));
            item.setText(12, getSafeText(entry.getServerIp()));
            item.setText(13, getSafeText(entry.getServerIpSubMask()));
            item.setText(14, getSafeText(entry.getServerPort()));
            item.setText(15, getSafeText(entry.getClient()));
            item.setText(16, getSafeText(entry.getClientId()));
            item.setText(17, getSafeText(entry.getClientIpUni()));
            item.setText(18, getSafeText(entry.getClientIpSubMask()));
            item.setText(19, getSafeText(entry.getClientPort()));

            // 处理列表类型的字段（保持原逻辑并简化）
            item.setText(20, entry.getsList() != null ? 
                String.join(", ", entry.getsList()) : "");
            item.setText(21, entry.getcList() != null ? 
                String.join(", ", entry.getcList()) : "");
        }
    }

    private static void initializeUIWithConfig() {
        loadGlobalDataToUI();
        loadActiveTableToUI();
    }

    private static String getSafeText(String value) {
        // 如果值为null，返回空字符串；否则返回原值
        return value == null ? "" : value;
    }
}
